package com.ppandroid.wifiap.manager

import android.content.Context
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.Build
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.NetworkInterface
import java.util.*

/**
 * WiFi热点管理器
 */
sealed class HotspotResult {
    object Success : HotspotResult()
    object NeedUserAction : HotspotResult()
    data class Error(val message: String) : HotspotResult()
}

class WifiHotspotManager(private val context: Context) {
    
    private val wifiManager: WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
    
    companion object {
        private const val TAG = "WifiHotspotManager"
        internal const val SSID = "WiFi_AP_12345"
        internal const val PASSWORD = "12345678"
        private const val SECURITY_TYPE = WifiConfiguration.KeyMgmt.WPA_PSK
    }
    
    /**
     * 启动WiFi热点
     */
    suspend fun startHotspot(): HotspotResult = withContext(Dispatchers.IO) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                // Android 8.0及以上版本需要使用新的API
                return@withContext startHotspotApi26()
            } else {
                // Android 8.0以下版本使用传统方法
                return@withContext if (startHotspotLegacy()) HotspotResult.Success else HotspotResult.Error("启动热点失败")
            }
        } catch (e: Exception) {
            Log.e(TAG, "启动热点失败", e)
            HotspotResult.Error("启动热点异常: ${e.message}")
        }
    }
    
    /**
     * 停止WiFi热点
     */
    suspend fun stopHotspot(): Boolean = withContext(Dispatchers.IO) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return@withContext stopHotspotApi26()
            } else {
                return@withContext stopHotspotLegacy()
            }
        } catch (e: Exception) {
            Log.e(TAG, "停止热点失败", e)
            false
        }
    }
    
    /**
     * 检查热点是否正在运行
     */
    fun isHotspotRunning(): Boolean {
        // Android 8.0+ 使用系统API判断热点状态
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val method = wifiManager.javaClass.getMethod("isWifiApEnabled")
                method.invoke(wifiManager) as? Boolean ?: false
            } else {
                wifiManager.isWifiEnabled && getLocalIpAddress().isNotEmpty()
            }
        } catch (e: Exception) {
            Log.e(TAG, "判断热点状态失败", e)
            false
        }
    }
    
    /**
     * 获取热点SSID
     */
    fun getHotspotSsid(): String {
        // Android 8.0+ 尝试读取系统热点配置
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val config = wifiManager.javaClass.getMethod("getWifiApConfiguration").invoke(wifiManager)
                val ssidField = config?.javaClass?.getDeclaredField("SSID")
                ssidField?.isAccessible = true
                val ssid = ssidField?.get(config) as? String
                ssid ?: SSID
            } else {
                SSID
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取热点SSID失败", e)
            SSID
        }
    }
    
    /**
     * 获取热点密码
     */
    fun getHotspotPassword(): String {
        // Android 8.0+ 尝试读取系统热点配置
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val config = wifiManager.javaClass.getMethod("getWifiApConfiguration").invoke(wifiManager)
                val pwdField = config?.javaClass?.getDeclaredField("preSharedKey")
                pwdField?.isAccessible = true
                val pwd = pwdField?.get(config) as? String
                pwd ?: PASSWORD
            } else {
                PASSWORD
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取热点密码失败", e)
            PASSWORD
        }
    }
    
    /**
     * 获取本机IP地址
     */
    fun getLocalIpAddress(): String {
        try {
            val networkInterfaces = NetworkInterface.getNetworkInterfaces()
            while (networkInterfaces.hasMoreElements()) {
                val networkInterface = networkInterfaces.nextElement()
                val inetAddresses = networkInterface.inetAddresses
                while (inetAddresses.hasMoreElements()) {
                    val inetAddress = inetAddresses.nextElement()
                    if (!inetAddress.isLoopbackAddress && inetAddress.hostAddress.indexOf(':') < 0) {
                        val hostAddress = inetAddress.hostAddress
                        if (hostAddress.startsWith("192.168.") || hostAddress.startsWith("10.0.")) {
                            return hostAddress
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "获取IP地址失败", e)
        }
        return "192.168.43.1" // 默认IP
    }
    
    /**
     * Android 8.0及以上版本启动热点
     */
    @Suppress("DEPRECATION")
    private suspend fun startHotspotApi26(): HotspotResult {
        // 这里需要系统权限，普通APP无法自动开启热点，只能引导用户手动开启
        return HotspotResult.NeedUserAction
    }
    
    /**
     * Android 8.0以下版本启动热点
     */
    @Suppress("DEPRECATION")
    private suspend fun startHotspotLegacy(): Boolean {
        return try {
            // 创建WiFi配置
            val wifiConfig = WifiConfiguration().apply {
                SSID = WifiHotspotManager.SSID
                preSharedKey = "\"$PASSWORD\""
                allowedKeyManagement.set(SECURITY_TYPE)
                allowedProtocols.set(WifiConfiguration.Protocol.RSN)
                allowedProtocols.set(WifiConfiguration.Protocol.WPA)
                allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
                allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40)
                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104)
                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP)
                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
            }
            
            // 添加网络配置
            val networkId = wifiManager.addNetwork(wifiConfig)
            if (networkId != -1) {
                wifiManager.enableNetwork(networkId, true)
                wifiManager.setWifiEnabled(true)
                true
            } else {
                false
            }
        } catch (e: Exception) {
            Log.e(TAG, "Legacy 启动热点失败", e)
            false
        }
    }
    
    /**
     * Android 8.0及以上版本停止热点
     */
    private suspend fun stopHotspotApi26(): Boolean {
        return try {
            // 这里需要系统权限
            true
        } catch (e: Exception) {
            Log.e(TAG, "API 26+ 停止热点失败", e)
            false
        }
    }
    
    /**
     * Android 8.0以下版本停止热点
     */
    private suspend fun stopHotspotLegacy(): Boolean {
        return try {
            wifiManager.setWifiEnabled(false)
            true
        } catch (e: Exception) {
            Log.e(TAG, "Legacy 停止热点失败", e)
            false
        }
    }
}
